package com.example.a2022110341

import android.Manifest
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.database.Cursor
import android.net.Uri
import android.os.Bundle
import android.os.IBinder
import android.provider.MediaStore
import android.widget.Button
import android.widget.SeekBar
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class MainActivity : AppCompatActivity() {
    private val REQUEST_PERMISSION = 1
    private var musicService: MusicService? = null
    private var isBound = false
    private lateinit var seekBar: SeekBar
    private lateinit var playButton: Button
    private lateinit var pauseButton: Button
    private lateinit var stopButton: Button
    private lateinit var prevButton: Button
    private lateinit var nextButton: Button
    private val musicFiles = mutableListOf<String>()
    private var currentTrackIndex = 0

    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val binder = service as MusicService.MusicBinder
            musicService = binder.getService()
            isBound = true
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            isBound = false
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        playButton = findViewById(R.id.playButton)
        pauseButton = findViewById(R.id.pauseButton)
        stopButton = findViewById(R.id.stopButton)
        prevButton = findViewById(R.id.prevButton)
        nextButton = findViewById(R.id.nextButton)
        seekBar = findViewById(R.id.seekBar)

        // 检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), REQUEST_PERMISSION)
        } else {
            getMusicFiles()
        }

        val intent = Intent(this, MusicService::class.java)
        bindService(intent, serviceConnection, BIND_AUTO_CREATE)

        playButton.setOnClickListener {
            if (isBound) {
                musicService?.play(musicFiles[currentTrackIndex])
            }
        }
        pauseButton.setOnClickListener {
            if (isBound) {
                musicService?.pause()
            }
        }
        stopButton.setOnClickListener {
            if (isBound) {
                musicService?.stop()
            }
        }
        prevButton.setOnClickListener {
            if (isBound) {
                currentTrackIndex = if (currentTrackIndex > 0) currentTrackIndex - 1 else musicFiles.size - 1
                musicService?.play(musicFiles[currentTrackIndex])
            }
        }
        nextButton.setOnClickListener {
            if (isBound) {
                currentTrackIndex = (currentTrackIndex + 1) % musicFiles.size
                musicService?.play(musicFiles[currentTrackIndex])
            }
        }
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser && isBound) {
                    musicService?.seekTo(progress)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })
        Thread {
            while (true) {
                if (isBound && musicService?.isPlaying() == true) {
                    seekBar.progress = musicService?.getCurrentPosition() ?: 0
                }
                Thread.sleep(1000)
            }
        }.start()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (isBound) {
            unbindService(serviceConnection)
            isBound = false
        }
    }

    private fun getMusicFiles() {
        val contentResolver = contentResolver
        val uri: Uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
        val projection = arrayOf(
            MediaStore.Audio.Media._ID,
            MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media.DATA
        )
        val cursor: Cursor? = contentResolver.query(uri, projection, null, null, null)
        cursor?.use {
            while (it.moveToNext()) {
                val titleIndex = it.getColumnIndex(MediaStore.Audio.Media.TITLE)
                val artistIndex = it.getColumnIndex(MediaStore.Audio.Media.ARTIST)
                val dataIndex = it.getColumnIndex(MediaStore.Audio.Media.DATA)
                if (titleIndex >= 0 && artistIndex >= 0 && dataIndex >= 0) {
                    val title = it.getString(titleIndex)
                    val artist = it.getString(artistIndex)
                    val data = it.getString(dataIndex)
                    musicFiles.add(data)
                }
            }
        }
    }
}